<?php

require_once LIBRARIES_ENTITIES_DATABASE;
require_once LIBRARIES_ENTITIES_USERS;
require_once LIBRARIES_ENTITIES_GROUPS;
require_once LIBRARIES_ENTITIES_GROUPUSERS;

require_once LIBRARIES_TOOLS_UTILITY;
require_once LIBRARIES_TOOLS_XTEMPLATE;
require_once LIBRARIES_TOOLS_PAGERBACKEND;

class ProfileController {

    public function invoke() {

        // function list
        $groupFunctions = $_SESSION['groupFunctions'];

        // directory path
        $dir = dirname(__FILE__);

        $action = '';
        if (isset($_POST['hdAction'])) {
            $action = $_POST['hdAction'];
        }


        switch ($action) {
            case 'edit':
            case 'editAndExit':

                $userID = $_POST['hdID'];
                $fullName = $_POST['txtFullName'];
                $email = $_POST['txtEmail'];


                if (trim($_POST['txtPassword']) != '') {
                    $password = md5($_POST['txtPassword']);
                } else {
                    $password = $_POST['hdOldPassword'];
                }
                $status = $_POST['hdStatus'];


                $result = $this->updateUser($userID, $fullName, $password, $email, $status);

                if ($result == OK) {
                    if ($action == 'edit') {
                        Utility::messageBox('Sửa thành công');
                    } else {
                        Utility::redirect(".");
                    }
                }
                break;
            case 'cancel':
                Utility::redirect(".");
                break;
        }




        $userID = $_SESSION["session"]["sUserID"];
        $user = $this->getUserByID($userID);

        if ($user != null) {

            $viewFile = $dir . '/views/user_edit.html';
            $xtemplate = new XTemplate($viewFile);

            // groups of user
            $groupsOfUser = $this->getGroupListByUserID($user->getID());

            $xtemplate->assign('USER_ID', $user->getID());
            $xtemplate->assign('USER_NAME', $user->getUserName());
            $xtemplate->assign('FULL_NAME', $user->getFullname());
            $xtemplate->assign('EMAIL', $user->getEmail());
            $xtemplate->assign('PASSWORD', $user->getPassword());
            $xtemplate->assign('STATUS', $user->getStatus());

            // show group list
            $this->printGroupList($xtemplate, $groupsOfUser[0]->getGroupID());


            $xtemplate->parse('main');
            $xtemplate->out('main');
        } else {
            Utility::redirect('.');
        }
    }

    private function getGroupList() {
        $db = new Database();
        try {
            $group = new Groups();
            $result = $group->getList($db);
            $db->submitChanges();
            return $result;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

    private function printGroupList($xtemplate, $selectedID = null) {

        $groups = $this->getGroupList();

        foreach ($groups as $group) {
            $xtemplate->assign('GROUP_NAME', $group->getName());
            $xtemplate->assign('GROUP_ID', $group->getID());

            if ($selectedID != null) {
                if ($selectedID == $group->getID()) {
                    $xtemplate->assign('SELECTED', 'selected');
                } else {
                    $xtemplate->assign('SELECTED', '');
                }
            } else {
                if (isset($_POST['slGroupID'])) {

                    if ($_POST['slGroupID'] == $group->getID()) {
                        $xtemplate->assign('SELECTED', 'selected');
                    } else {
                        $xtemplate->assign('SELECTED', '');
                    }
                } else if (isset($_GET['groupID'])) {

                    if ($_GET['groupID'] == $group->getID()) {
                        $xtemplate->assign('SELECTED', 'selected');
                    } else {
                        $xtemplate->assign('SELECTED', '');
                    }
                } else {
                    $xtemplate->assign('SELECTED_CATEGORY', '');
                }
            }
            $xtemplate->parse('main.group_list');
        }
    }

    private function updateUser($userID, $fullName, $password, $email, $status) {
        $db = new Database();
        try {
            $user = new Users();
            $user->setID($userID);
            $user->setFullname($fullName);
            $user->setEmail($email);
            $user->setPassword($password);
            $user->setStatus($status);
            $user->update($db);
            $db->submitChanges();
            return OK;
        } catch (PDOException $ex) {
            echo $ex->getMessage();
            $db->rollback();
            exit();
        }
    }

    private function getUserByID($userID) {
        $db = new Database();
        try {
            $user = new Users();
            $user->setID($userID);
            $result = $user->getByID($db);
            $db->submitChanges();
            return $result;
        } catch (PDOException $ex) {
            echo $ex->getMessage();
            $db->rollback();
            exit();
        }
    }

    private function getUserByUserName($userName) {
        $db = new Database();
        try {
            $user = new Users();
            $user->setUserName($userName);
            $result = $user->getByUserName($db);
            $db->submitChanges();
            return $result;
        } catch (PDOException $ex) {
            echo $ex->getMessage();
            $db->rollback();
            exit();
        }
    }

    private function getGroupListByUserID($userID) {
        $db = new Database();
        try {
            $groupUser = new GroupUsers();
            $groupUser->setUserID($userID);

            $result = $groupUser->getListByUserID($db);
            $db->submitChanges();
            return $result;
        } catch (Exception $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

}

?>
